package com.flute.haflute.monitor;

import sun.management.ManagementFactory;

import com.sun.management.OperatingSystemMXBean;

public class Memory {
	
	OperatingSystemMXBean osmxb = null;
	static Memory memory = null;
	Runtime runtime = Runtime.getRuntime();
	
	public static Memory getInstance(){
		if(memory == null){
			memory = new Memory();
		}
		return memory;
	}
	
	Memory(){
		    osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
	}
	
	/**
	 * 操作系统的总物理内存
	 * @return
	 */
	public long getTotalPhysicalMemorySize(){
		return osmxb.getTotalPhysicalMemorySize();
	}
	/**
	 * 操作系统空闲的物理内存
	 * @return
	 */
	public long getFreePhysicalMemorySize(){
		return osmxb.getFreePhysicalMemorySize();
	}
	/**
	 * 获取操作系统内存占用率
	 * 
	 * @return
	 */
	public double getOSMemoryRate() {
		
		// 总的物理内存
		long totalMemorySize = getTotalPhysicalMemorySize();
		// 剩余的物理内存
		long freePhysicalMemorySize = getFreePhysicalMemorySize();

		return 1 - 1.0 * freePhysicalMemorySize / totalMemorySize;
	}

	/**
	 * 获取JVM内存占用率
	 * 
	 * @return
	 */
	public String getJVMMemoryRate() {
		

		double freeMemory = (double) runtime.freeMemory() / (1024 * 1024);
		// 内存总量
		double totalMemory = (double) runtime.totalMemory() / (1024 * 1024);
		// 已用内存
		double usedMemory = Math.round(totalMemory - freeMemory);
		
		java.text.NumberFormat numberFormat = java.text.NumberFormat.getPercentInstance();   
		String percentUsed = numberFormat.format(((double)usedMemory/(double)totalMemory));

		return percentUsed;
	}
	public double getTotalMemory(){
		return  (double) runtime.totalMemory() / (1024 * 1024);
	}
	public double getUsedMemory(){
		return  Math.round(getTotalMemory() - getFreeMemory());
	}
	public double getFreeMemory(){
		return  (double) runtime.freeMemory() / (1024 * 1024);
	}

}
